package com.eedi.framework.job.service;

import com.eedi.framework.common.pojo.PageResult;
import com.eedi.framework.job.controller.org.vo.log.OrgJobLogPageReq;
import com.eedi.framework.job.dal.dataobject.OrgJobLogDO;
import com.eedi.framework.job.dal.mapper.OrgJobLogMapper;
import com.eedi.framework.job.enums.OrgJobLogStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * Job 日志 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class OrgJobLogServiceImpl implements OrgJobLogService {

    @Resource
    private OrgJobLogMapper orgJobLogMapper;

    @Override
    public String createJobLog(String jobId, LocalDateTime beginTime,
                             String jobHandlerName, String jobHandlerParam, Integer executeIndex) {
        OrgJobLogDO log = OrgJobLogDO.builder().orgJobId(jobId).handlerName(jobHandlerName)
                .handlerParam(jobHandlerParam).executeIndex(executeIndex)
                .beginTime(beginTime).status(OrgJobLogStatusEnum.RUNNING.getCode()).build();
        orgJobLogMapper.insert(log);
        return log.getOrgJobLogId();
    }

    @Override
    @Async
    public void updateJobLogResultAsync(String logId, LocalDateTime endTime, Integer duration, boolean success, String result) {
        try {
            OrgJobLogDO updateObj = OrgJobLogDO.builder().orgJobLogId(logId).endTime(endTime).duration(duration)
                    .status(success ? OrgJobLogStatusEnum.SUCCESS.getCode() : OrgJobLogStatusEnum.FAILURE.getCode())
                    .result(result).build();
            orgJobLogMapper.updateById(updateObj);
        } catch (Exception ex) {
            log.error("[updateJobLogResultAsync][logId({}) endTime({}) duration({}) success({}) result({})]",
                    logId, endTime, duration, success, result);
        }
    }

    @Override
    @SuppressWarnings("DuplicatedCode")
    public Integer cleanJobLog(Integer exceedDay, Integer deleteLimit) {
        int count = 0;
        LocalDateTime expireDate = LocalDateTime.now().minusDays(exceedDay);
        // 循环删除，直到没有满足条件的数据
        for (int i = 0; i < Short.MAX_VALUE; i++) {
            int deleteCount = orgJobLogMapper.deleteByCreateTimeLt(expireDate, deleteLimit);
            count += deleteCount;
            // 达到删除预期条数，说明到底了
            if (deleteCount < deleteLimit) {
                break;
            }
        }
        return count;
    }

    @Override
    public OrgJobLogDO getJobLog(String id) {
        return orgJobLogMapper.selectById(id);
    }

    @Override
    public PageResult<OrgJobLogDO> getJobLogPage(OrgJobLogPageReq pageReqVO) {
        return orgJobLogMapper.selectPage(pageReqVO);
    }

}
